package com.junxonline.plat.service.auth.impl;

import com.junxonline.common.util.JWTUtils;
import com.junxonline.plat.dao.SystemUserDAO;
import com.junxonline.plat.model.SystemUser;
import com.junxonline.common.util.CommonUtils;
import com.junxonline.plat.service.auth.LoginService;
import com.junxonline.plat.service.exception.PlatBizException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private SystemUserDAO systemUserDAO;

    @Override
    public Map<String, Object> login(String username, String password) {

        SystemUser user = systemUserDAO.findByUsername(username);
        if (CommonUtils.isEmpty(user)) {
            throw PlatBizException.ACCOUNT_IS_NOT_FINDED;
        }


        user = systemUserDAO.findByUsernameAndPassword(user.getUsername(), password);

        if (CommonUtils.isEmpty(user)) {
            return null;
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        // 生成Token
        String token = JWTUtils.sign(username, password);

        // TODO 将Token和用户信息存入Redis

        returnMap.put("userId", user.getUserId());
        returnMap.put("userInfo", user);
        returnMap.put("token", token);
        return returnMap;

    }
}
